package com.wuseguang.springcloud.Filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;

public class RequestParameterWrapper extends HttpServletRequestWrapper
{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	 private Map<String, String[]> params = new HashMap<String, String[]>();

	    public RequestParameterWrapper(HttpServletRequest request) {
	        super(request);
	        //将现有参数传递给params
	        this.params.putAll(request.getParameterMap());
	    }

	/**
	 * 重载构造函数
	 * @param request
	 * @param paramMap 而外的参数
	 */
	public RequestParameterWrapper(HttpServletRequest request, Map<String, Object> paramMap) {
	        super(request);
	        addParameters(paramMap);
	    }

	    //添加额外参数
	    public void addParameters(Map<String, Object> extraParams) {
	        for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
	            addParameter(entry.getKey(), entry.getValue());
	        }
	    }

	    public String getParam(String name) {
	    	//判断获取名字为空
	    	if (name!=null && params!=null && params.containsKey(name)){
	    	    Object value = params.get(name);

	    	    if (value instanceof String[]){
	    	    	return ((String[])value)[0];
	    	    }
	    	    //返回获取的参数
	    		return (String)value;
	    	}
	    	//没有找到相对应的参数
	    	return null;
	    }

	    public void addParameter(String name, Object value) {
	        if (value != null) {

	        	if (params.containsKey(name)){
	        		logger.info("key exists ["+name+"],value="+params.get(name));
	        		params.remove(name);
	        	}

	            if (value instanceof String[]) {
	                params.put(name, (String[]) value);
	            }else if (value instanceof String) {
	                params.put(name, new String[]{(String) value});
	            }else {
	                params.put(name, new String[]{String.valueOf(value)});
	            }
	        }
	    }

}
